﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Globalization;

namespace Silvermoon.Controls
{
    public class TimePicker:TextBox
    {
        private string format = CultureInfo.CurrentUICulture.DateTimeFormat.ShortTimePattern;

        private TimeSpan time;

        public TimePicker()
            : base()
        {
            StyleName = "TimePicker";
            AllowPress = true;
            OnTimeChanged();
        }

        /// <summary>
        /// Gets or sets the format pattern which converts the time to string.
        /// </summary>
        public string Format
        {
            get { return format; }
            set
            {
                if (format != value)
                {
                    format = value;
                    OnTimeChanged();
                }
            }
        }

        public override bool ReadOnly
        {
            get { return true; }
            set { }
        }

        public TimeSpan Time
        {
            get { return time; }
            set
            {
                if (time != value)
                {
                    time = value;
                    OnTimeChanged();
                }
            }
        }

        protected virtual void OnTimeChanged()
        {
            DateTime dt = new DateTime(1, 1, 1, time.Hours, time.Minutes, time.Seconds);
            Text = dt.ToString(format);
        }

        protected internal override void OnTap(TapEventArgs e)
        {
            base.OnTap(e);
            if (!e.Handled)
            {
                TimePickerDialog dlg = new TimePickerDialog { Time = this.time };
                dlg.Selected += new EventHandler<TimeSpanEventArgs>(OnTimeSelected);
                dlg.Shown += new EventHandler(OnDialogShown);
                dlg.Hiding += new EventHandler(OnDialogHiding);
                dlg.Show();
            }
        }

        protected override void CheckInputControl()
        {
            Window w = Window;
            if (w != null) w.IsKeyboardVisible = false;
        }

        void OnDialogHiding(object sender, EventArgs e)
        {
            Window w = Window;
            if (w != null) w.Visible = true;
        }

        void OnDialogShown(object sender, EventArgs e)
        {
            Window w = Window;
            if (w != null) w.Visible = false;
        }

        void OnTimeSelected(object sender, TimeSpanEventArgs e)
        {
            Time = e.Time;
        }

    }
}
